package com.ghxxzx.dagl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ghxxzx.dagl.entity.Fg;
import com.ghxxzx.dagl.entity.Hybz;
import com.ghxxzx.dagl.entity.Hybz;
import com.ghxxzx.dagl.entity.User;
import com.ghxxzx.dagl.exceptions.JyException;
import com.ghxxzx.dagl.mapper.HybzMapper;
import com.ghxxzx.dagl.service.HybzService;
import com.ghxxzx.dagl.utils.NullUtils;
import com.ghxxzx.dagl.utils.PageResultUtils;
import com.ghxxzx.dagl.vo.PageQuery;
import com.ghxxzx.dagl.vo.PageResult;
import com.ghxxzx.dagl.vo.ResultEntity;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * @Author: 刘华
 * @Date: 2020/9/28 14:58
 * @Version 1.0
 */
@Service
@Transactional
public class HybzServiceImpl implements HybzService {
    @Autowired
    private HybzMapper hybzMapper;
    @Value("${hxbz.fj}")
    private String path;
    @Override
    public ResultEntity addHxbz(MultipartFile multipartFile, User user,Hybz hybz) {
        String name = multipartFile.getOriginalFilename();
//        multipartFile.getContentType();
        int i = name.lastIndexOf(".");
//        String[] split = name.split("\\.");
        String substring = name.substring(i + 1);
        if (!substring.equals("pdf")){
            throw new JyException("请上传pdf文件");
        }
        QueryWrapper<Hybz> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name.substring(0,i));
        Hybz selectOne = hybzMapper.selectOne(wrapper);
        if (selectOne!=null){
            hybz.setId(selectOne.getId());
            hybz.setName(name.substring(0,i));
            hybzMapper.updateById(hybz);
        }else {
            hybz.setName(name.substring(0,i));
            hybzMapper.insert(hybz);
        }
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }
        InputStream inputStream = null;
        FileOutputStream fileOutputStream1 = null;
        try {
            inputStream=multipartFile.getInputStream();
            fileOutputStream1 = new FileOutputStream(path + multipartFile.getOriginalFilename());
            IOUtils.copy(inputStream, fileOutputStream1);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (fileOutputStream1 != null) {
                try {
                    fileOutputStream1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultEntity.ok();
    }

    @Override
    public ResultEntity queryAll() {
        QueryWrapper<Hybz> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("id");
        List<Hybz> hybzs = hybzMapper.selectList(wrapper);
        return ResultEntity.ok(hybzs);
    }

    @Override
    public void downloadFg(String name, HttpServletRequest request, HttpServletResponse response) {
        String filepath = path + name + ".pdf";
        File file = new File(filepath);
        if (!file.exists()) {
            throw new JyException("文件不存在");
        }
        OutputStream out = null;
        BufferedInputStream is = null;
        byte[] b = new byte[4096];
        int len = 1024;
        // 清空response
        response.reset();
        response.setContentType("application/x-download");//设置response内容的类型 普通下载类型
        try {
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//设置头部信息
            out = response.getOutputStream();
            is = new BufferedInputStream(new FileInputStream(file));
            while ((len = is.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public ResultEntity querykeyword(String keyword) {
        QueryWrapper<Hybz> wrapper = new QueryWrapper<>();
        if (NullUtils.isNotNull(keyword)){
            wrapper.like("name",keyword);
        }
        List<Hybz> hybzs = hybzMapper.selectList(wrapper);
        return ResultEntity.ok(hybzs);
    }

    @Override
    public ResultEntity deleteById(Integer id) {
        Hybz hybz = hybzMapper.selectById(id);
        hybzMapper.deleteById(id);
        String filepath = path + hybz.getName() + ".pdf";
        File file = new File(filepath);
        if (!file.exists()){
            throw new JyException("文件不存在");
        }
        file.delete();
        return ResultEntity.ok();
    }
}
